package com.example.myapplication1.publishFriendCircle;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Vibrator;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;

import androidx.annotation.AnimRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication1.R;


/**
 * 滑动或拖拽帮助类，理论上是应该可以支持所有列表View的，这里只支持了RecyclerView
 * <p>
 * Created by superchen on  2017/9/11
 * The last edit time       2017/9/11
 */
public class RecyItemTouchHelperCallBack<T, VH extends RecyclerView.ViewHolder> extends ItemTouchHelper.Callback {

    public static final float ALPHA_FULL = 1.0f;

    private ItemTouchAdapter<T, VH> mAdapter;
    private DragListener<T, VH> dragListener;

    /**
     * 是否需要侧滑删除
     */
    private boolean isSwipeEnable = false;

//    /**
//     * 需要固定顺序不允许拖拽的List
//     */
//    private List<Integer> mCannotDragIndexList;

    private boolean actionUp;

    public RecyItemTouchHelperCallBack(ItemTouchAdapter<T, VH> adapter) {
        mAdapter = adapter;
    }

    @Override
    public int getMovementFlags(RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
                    ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        } else {
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
            int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
            return makeMovementFlags(dragFlags, swipeFlags);
        }
//        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//        int dragFlags = 0;
//        int swipeFlags = 0;
//        if (layoutManager instanceof GridLayoutManager || layoutManager instanceof StaggeredGridLayoutManager) {
//            // 如果是Grid布局，则不能滑动，只能上下左右拖动
//            dragFlags =
//                    ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//            swipeFlags = 0;
//        } else if (layoutManager instanceof LinearLayoutManager) {
//            // 如果是纵向Linear布局，则能上下拖动，左右滑动
//            if (((LinearLayoutManager) layoutManager).getOrientation() == LinearLayoutManager.VERTICAL) {
//                dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//                swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//            } else {
//                // 如果是横向Linear布局，则能左右拖动，上下滑动
//                swipeFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//                dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//            }
//        }
//        return makeMovementFlags(dragFlags, swipeFlags); //该方法指定可进行的操作
    }

    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        final int fromPosition = viewHolder.getAdapterPosition();
        final int toPosition = target.getAdapterPosition();
        if (!checkCanLongDrag(fromPosition, toPosition)) {
            return false;
        }
        if (null != dragListener) {
            dragListener.onDraging();
        }
        if (mAdapter != null) {
            mAdapter.onItemMove(fromPosition, toPosition);
        }
        return true;
    }

    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        if (mAdapter != null) {
            mAdapter.onItemRemove(viewHolder.getAdapterPosition());
//            int adapterPosition = viewHolder.getAdapterPosition();
//            mAdapter.notifyItemRemoved(adapterPosition);
//            if (mAdapter instanceof ItemTouchAdapter) {
//                ((ItemTouchAdapter) mAdapter).getData().remove(adapterPosition);
//            }
        }
    }

    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                            @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        if (null != dragListener) {
            final boolean isInArea = dragListener.checkIsInSpecialArea(c, recyclerView, viewHolder,
                    dX, dY, actionState, isCurrentlyActive);
            //是否用户自己操作RecyclerView视图的变化,数据不管
            final boolean userSelfDo = dragListener.stateIsInSpecialArea(isInArea, actionUp, viewHolder.getAdapterPosition());
            //如果给予该类操作且处于该区域且手指松开,则进行删除
            if (!userSelfDo && isInArea && actionUp) {
                viewHolder.itemView.setVisibility(View.INVISIBLE);
                if (mAdapter != null) {
                    mAdapter.onItemRemove(viewHolder.getAdapterPosition());
                }
                dragListener.doBothInAreaAndFingerUp(true, actionUp);
                actionUp = false;
                return;
            } else {
                dragListener.stateIsInSpecialArea(isInArea, actionUp, viewHolder.getAdapterPosition());
            }
        }
        if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
            View itemView = viewHolder.itemView;
            final float alpha = ALPHA_FULL - Math.abs(dX) / (float) itemView.getWidth();
            itemView.setAlpha(alpha);
        }
        super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
    }

    /**
     * 设置手指离开后ViewHolder的动画时间，在用户手指离开后调用
     */
    @Override
    public long getAnimationDuration(@NonNull RecyclerView recyclerView, int animationType, float animateDx, float animateDy) {
        //手指放开
        actionUp = true;
        return super.getAnimationDuration(recyclerView, animationType, animateDx, animateDy);
    }

    @Override
    public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
        if (null != viewHolder) {
            if (checkCanLongDrag(viewHolder.getAdapterPosition(), -1)) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    if (mAdapter != null && mAdapter.getContext() != null) {
                        Vibrator vibrator = (Vibrator) mAdapter.getContext().getSystemService(Context.VIBRATOR_SERVICE);
                        if (vibrator != null) {
                            vibrator.vibrate(50);
                        }
                    }
                    if (null != dragListener) {
                        dragListener.onPreDrag();
                    }
                    startItemScaleAni(viewHolder, true);
                }
            }
        }
        super.onSelectedChanged(viewHolder, actionState);
    }

    @Override
    public void clearView(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
        super.clearView(recyclerView, viewHolder);
        startItemScaleAni(viewHolder, false);
        viewHolder.itemView.setAlpha(ALPHA_FULL);
        viewHolder.itemView.setBackgroundColor(Color.WHITE);
        resetDragListenerBoth();
        if (null != dragListener) {
            dragListener.onReleasedDrag();
            dragListener.clearView();
        }
    }

    @Override
    public boolean isLongPressDragEnabled() {
        return false;
    }

    @Override
    public boolean isItemViewSwipeEnabled() {
        return isSwipeEnable;
    }

    private void resetDragListenerBoth() {
        if (null != dragListener) {
            dragListener.stateIsInSpecialArea(false, false, -1);
        }
        actionUp = false;
    }

    public void startItemScaleAni(RecyclerView.ViewHolder viewHolder, boolean bigger) {
        if (null != viewHolder) {
            if (bigger) {
                doScaleAni(viewHolder.itemView, R.anim.scale_from_100_to_110, false);
            } else {
                doScaleAni(viewHolder.itemView, R.anim.scale_from_110_to_100, true);
            }
        }
    }

    public boolean checkCanLongDrag(int fromOrLongClickPosition, int toPosition) {
        return null == mAdapter || mAdapter.getCannotDragIndexList() == null ||
                (!mAdapter.getCannotDragIndexList().contains(fromOrLongClickPosition) && (-1 == toPosition || !mAdapter.getCannotDragIndexList().contains(toPosition)));
    }

    public void setSwipeEnable(boolean swipeEnable) {
        isSwipeEnable = swipeEnable;
    }

    public void setDragListener(DragListener<T, VH> dragListener) {
        this.dragListener = dragListener;
    }

    public void doScaleAni(final View view, @AnimRes int animResId, boolean clearAnimation) {
        if (null == view) return;
        Animation animation = (Animation) AnimationUtils.loadAnimation(view.getContext(), animResId);
        if (clearAnimation) {
            animation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    view.clearAnimation();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        view.startAnimation(animation);
    }
}
